<?php

use app\admin\model\develop\Acuisitionscheme;
use app\common\model\Category;
use fast\Form;
use fast\Tree;
use think\Db;
use app\admin\model\statistics\Order as orderModel;

if (!function_exists('create_order_acuisitionscheme')){
    function create_order_acuisitionscheme($materialPlanData){

//                     根据条件查找符合条件的产品订单
        $order_detail = new \app\admin\model\statistics\Orderdetail;
        $order_detail_where['trademark_printing'] = $materialPlanData->trademark_printing;
        $order_detail_where['colour_id'] = $materialPlanData->colour_id;
        $order_detail_where['status'] = 0;
        $order_detail_data = collection($order_detail->where($order_detail_where)->select())->toArray();
        $flag = true;

        $acquisitionschemeArr = [];
        $orderDetailIdArr = [];
        //循环订单为订单生成领料方案
        foreach ($order_detail_data as $k=>$v){
            $acquisitionscheme_insert['order_id'] = $v['order_id'];
            $acquisitionscheme_insert['order_detail_id'] = $v['id'];
            $acquisitionscheme_insert['colour_id'] = $v['colour_id'];
            $acquisitionscheme_insert['material_plan_id'] = $materialPlanData->pid;

            $acquisitionschemeArr[] = $acquisitionscheme_insert;
//            $acquisitionscheme->save($acquisitionscheme_insert);

            //更新订单产品
            $orderIdArr[] = $v['order_id'];
            $orderDetailIdArr[] = $v['id'];
        }
        $acquisitionscheme = new Acuisitionscheme();
        $acquisitionscheme->saveAll($acquisitionschemeArr);
        $order_detail->where('id','in',$orderDetailIdArr)->setField('status',1);
        return $flag;
    }
}

if(!function_exists('is_has_received')){
    /**
     * 判断当前商标印字+色号+工序的组合是否存在收货记录
     * @param $trademark_printing
     * @param $colour_id
     * @param process_attribute_id
     * @return void
     */
    function is_has_received($trademark_printing,$colour_id,$process_attribute_id){
        $result = false;
        $where['od.trademark_printing'] = $trademark_printing;
        $where['r.colour_id'] = $colour_id;
        $where['r.process_attribute_id'] = $process_attribute_id;
        $re = Db::name('receiving')->alias('r')
            ->join('order_detail od','od.id = r.order_detail_id')
            ->where($where)->count();
        $result = $re>0?true:false;
        return $result;
    }
}

if(!function_exists('arr_include_arr')){
    /**
     * 判断数组2中是否包含另数组1的所有元素（一维数组）
     * @param $arr1
     * @param $arr2
     * @return void
     */
    function arr_include_arr($arr1,$arr2){
        $isset = true;
        foreach ($arr1 as $k=>$v){
            if(!in_array($v,$arr2)){
                $isset = false;
                break;
            }
        }
        return $isset;
    }
}

if(!function_exists('up_order_schedule')){
    //重新计算订单进度数据
    function up_order_schedule($orderId){
        if(!$orderId) return false;

        $result = true;
        //订单详情列表
        $orderWhere['order_id'] = $orderId;
        $orderWhere['process_detail'] = array('neq',NULL);
        $orderDetailArr = Db::name('order_detail')->where('order_id','eq',$orderId)->select();

        if($orderDetailArr && is_array($orderDetailArr)){
            $order['id'] = $orderId;
            $order['received'] = 0;
            $order['schedule'] = 0;

            $process_detail = [];
            foreach ($orderDetailArr as $k=>$v){
                //获取订单色号收取总数
                $orderDetail[$k]['id'] = $v['id'];
                $orderDetail[$k]['colour_received'] = get_colour_received_by_id($v['id']);

                $orderDetail[$k]['colour_schedule'] = 0; //色号进度

                if(boolval(trim($v['process_detail'])) && $orderDetail[$k]['colour_received'] !=0){
                    //重新计算工序详情
                    $process_detail[$k] = \GuzzleHttp\json_decode($v['process_detail'],true);
                    if($process_detail[$k] && is_array($process_detail[$k])){
                        foreach ($process_detail[$k] as $k2=>$v2){
                            //重新赋值工序进度
                            $process_detail[$k][$k2]['schedule'] = $v2['quantity']/$v['quantity'];

                            //重新计算工序权重
                            $process_detail[$k][$k2]['weights'] = ($v2['quantity']/$orderDetail[$k]['colour_received'])*$process_detail[$k][$k2]['schedule'];
                            //订单明细色号进度累加
                            $orderDetail[$k]['colour_schedule'] += $process_detail[$k][$k2]['weights'];
                        }

                        //格式化数据
                        foreach ($process_detail[$k] as $k2=>$v2){
                            $process_detail[$k][$k2]['schedule'] = round($process_detail[$k][$k2]['schedule']*100,2);
                            $process_detail[$k][$k2]['weights'] = round($process_detail[$k][$k2]['weights']*100,2);
                        }
                        $orderDetail[$k]['process_detail'] = json_encode($process_detail[$k],JSON_UNESCAPED_UNICODE );
                    }

                    $order['received'] += get_colour_received_by_id($v['id']);
                }
            }

            foreach ($orderDetailArr as $k=>$v){
                //订单色号权重
                $orderDetail[$k]['colour_weights'] = $orderDetail[$k]['colour_received']/$order['received']*$orderDetail[$k]['colour_schedule'];
                //订单进度
                $order['schedule'] += $orderDetail[$k]['colour_weights'];
            }

            //格式化数据
            $order['schedule'] = round($order['schedule']*100,2);
            $order['status'] = $order['schedule']>100?0:1;

            foreach ($orderDetail as $k=>$v){
                $orderDetail[$k]['colour_weights'] = round($orderDetail[$k]['colour_weights']*100,2);
                $orderDetail[$k]['colour_schedule'] = round($orderDetail[$k]['colour_schedule']*100,2);
            }


            $orderModel = new orderModel();

            $orderModel->isUpdate(true)->update($order);

//            if ($up_order){
                $orderDetailModel = new \app\admin\model\statistics\Orderdetail();
                foreach ($orderDetail as $k=>$v){
                    $up_order_detail = $orderDetailModel->isUpdate(true)->where('id','eq',$v['id'])->update($v);
//                    if(!$up_order_detail) $result = false;break;
                }
//            }else{
//                $result = false;
//            }

        }
        return $result;
    }
}


if (!function_exists('add_order_process')) {
    /**
     * @param $trademark_printing
     * @param $colour_id
     * @return void
     * 给订单添加工序明细（添加订单明细或者添加商品工序时候调用）
     */
    function add_order_process($trademark_printing,$colour_id){
        $processModel = new \app\admin\model\other\Process();
        //获取当前商品所需工序信息
        $process = new \app\admin\model\other\Process();
        $where['$trademark_printing'] = $trademark_printing;
        $where['$colour_id'] = $colour_id;
        $processInfo = collection($process->where($where)->select())->toArray();
        if(count($processInfo)){
            $processList = explode(',',$processInfo[0]['process_attribute_ids']);
//                                    $orderDetail['colour_received'] = $orderDetialData['quantity']*count(explode(',',$p_re[0]['process_attribute_ids'])); //色号收取总数 固定值
        }else{
            $processInfo->error('还未添加当前商品的生产工序');
        }

    }
}

if (!function_exists('get_order_schedule')) {
    //获取订单进度信息
    function get_order_schedule($orderid,$orderdetialid,$colour_schedule){
        $result = $colour_schedule;

        $orderDetialmodel = new \app\admin\model\statistics\Orderdetail();

//        查询非当前订单色号权重
        $where['order_id'] = $orderid;
        $where['id'] = array('neq',$orderdetialid);

        $re = $orderDetialmodel->where($where)->sum('colour_weights');
//        p($re);
        $result += $re/100;

        return $result;
    }
}

/**
 * @param $id
 * @param $colour_schedule
 * @return void
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * 获取新的订单详情色号进度
 */
function get_colour_schedule($id,$process_id,$colour_schedule){
//    p($colour_schedule);
    $result = $colour_schedule;
    $orderDetialmodel = new \app\admin\model\statistics\Orderdetail();
    $orderDetialWhere2['id'] = $id;
    $re = collection($orderDetialmodel->where($orderDetialWhere2)->select())->toArray();
    $processArr = json_decode($re[0]['process_detail'],true);
    if($processArr){
        foreach ($processArr as $k=>$v){
            if($v['process_attribute'] != $process_id){
//                [{"process_attribute":"1","quantity":1000000,"schedule":0,"weights":0},{"process_attribute":"2","quantity":0,"schedule":0,"weights":0},{"process_attribute":"3","quantity":0,"schedule":0,"weights":0}]
                $result += $v['weights']/100;
            }
        }
    }

    return $result;
}


/**
 * @param $orderid
 * @return float|int
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * 根据订购单id获取订单收取总量
 */

function get_order_received_by_id($orderid=''){
    $orderDetialmodel = new \app\admin\model\statistics\Orderdetail();
    $orderProcess = new \app\admin\model\other\Process();
    $result = 0;
    //获取订单明细表数据
    $orderDetialWhere2['order_id'] = $orderid;
    $re = collection($orderDetialmodel->where($orderDetialWhere2)->select())->toArray();

    if(count($re)>0){
        $order['received'] ='0';
        foreach ($re as $k=>$v){
            $w2['trademark_printing'] = $v['trademark_printing'];
            $proc = collection($orderProcess->where($w2)->select())->toArray();
            if(count($proc)>0){
                foreach ($proc as $k2=>$v2){
                    $colourArr = explode(',',$v2['colour_ids']);
                    if(in_array($v['colour_id'],$colourArr)){
                        $procArr = explode(',',$v2['process_attribute_ids']);
                        $result +=count($procArr)*$v['quantity'];//订单收取总数  固定值
                        break;
                    }
                }
            }
        }
    }
    return $result;
}

/**
 * @param $order_detail_id
 * @return float|int
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * 根据订单产品id获取订单产品色号收取总数
 */
function get_colour_received_by_id($order_detail_id){

    $result = 0;
    $orderProcess = new \app\admin\model\other\Process();
    $orderDetialmodel = new \app\admin\model\statistics\Orderdetail();
    $res= collection($orderDetialmodel->where('id','eq',$order_detail_id)->select())->toArray();

    $w2['trademark_printing'] = $res[0]['trademark_printing'];
    $proc = collection($orderProcess->where($w2)->select())->toArray();

    if(count($proc)>0){
        foreach ($proc as $k2=>$v2){
            $colourArr = explode(',',$v2['colour_ids']);
            if(in_array($res[0]['colour_id'],$colourArr)){
                $procArr = explode(',',$v2['process_attribute_ids']);
                $result =count($procArr)*$res[0]['quantity'];//订单收取总数  固定值
                break;
            }
        }
    }
    return $result;
}

if(!function_exists('is_set_material')){
    /**
     * @param $itme
     * @param $Arr
     * @return void
     * 是否存在相同数据原料的发料数据
     */
    function is_set_material($itme,$Arr){
        $isste = false;
        foreach ($Arr as $k=>$v){
            if($itme['material']==$v['material'] && $itme['material_colour']==$v['material_colour']){
                $isste = true;
                break;
            }
        }
        return $isste;
    }
}

if (!function_exists('build_select')) {

    /**
     * 生成下拉列表
     * @param string $name
     * @param mixed  $options
     * @param mixed  $selected
     * @param mixed  $attr
     * @return string
     */
    function build_select($name, $options, $selected = [], $attr = [])
    {
        $options = is_array($options) ? $options : explode(',', $options);
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        return Form::select($name, $options, $selected, $attr);
    }
}

if (!function_exists('build_radios')) {

    /**
     * 生成单选按钮组
     * @param string $name
     * @param array  $list
     * @param mixed  $selected
     * @return string
     */
    function build_radios($name, $list = [], $selected = null)
    {
        $html = [];
        $selected = is_null($selected) ? key($list) : $selected;
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        foreach ($list as $k => $v) {
            $html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::radio($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
        }
        return '<div class="radio">' . implode(' ', $html) . '</div>';
    }
}

if (!function_exists('build_checkboxs')) {

    /**
     * 生成复选按钮组
     * @param string $name
     * @param array  $list
     * @param mixed  $selected
     * @return string
     */
    function build_checkboxs($name, $list = [], $selected = null)
    {
        $html = [];
        $selected = is_null($selected) ? [] : $selected;
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        foreach ($list as $k => $v) {
            $html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::checkbox($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
        }
        return '<div class="checkbox">' . implode(' ', $html) . '</div>';
    }
}


if (!function_exists('build_category_select')) {

    /**
     * 生成分类下拉列表框
     * @param string $name
     * @param string $type
     * @param mixed  $selected
     * @param array  $attr
     * @param array  $header
     * @return string
     */
    function build_category_select($name, $type, $selected = null, $attr = [], $header = [])
    {
        $tree = Tree::instance();
        $tree->init(Category::getCategoryArray($type), 'pid');
        $categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = $header ? $header : [];
        foreach ($categorylist as $k => $v) {
            $categorydata[$v['id']] = $v['name'];
        }
        $attr = array_merge(['id' => "c-{$name}", 'class' => 'form-control selectpicker'], $attr);
        return build_select($name, $categorydata, $selected, $attr);
    }
}

if (!function_exists('build_toolbar')) {

    /**
     * 生成表格操作按钮栏
     * @param array $btns 按钮组
     * @param array $attr 按钮属性值
     * @return string
     */
    function build_toolbar($btns = null, $attr = [])
    {
        $auth = \app\admin\library\Auth::instance();
        $controller = str_replace('.', '/', strtolower(think\Request::instance()->controller()));
        $btns = $btns ? $btns : ['refresh', 'add', 'edit', 'del', 'import'];
        $btns = is_array($btns) ? $btns : explode(',', $btns);
        $index = array_search('delete', $btns);
        if ($index !== false) {
            $btns[$index] = 'del';
        }
        $btnAttr = [
            'refresh' => ['javascript:;', 'btn btn-primary btn-refresh', 'fa fa-refresh', '', __('Refresh')],
            'add'     => ['javascript:;', 'btn btn-success btn-add', 'fa fa-plus', __('Add'), __('Add')],
            'edit'    => ['javascript:;', 'btn btn-success btn-edit btn-disabled disabled', 'fa fa-pencil', __('Edit'), __('Edit')],
            'del'     => ['javascript:;', 'btn btn-danger btn-del btn-disabled disabled', 'fa fa-trash', __('Delete'), __('Delete')],
            'import'  => ['javascript:;', 'btn btn-info btn-import', 'fa fa-upload', __('Import'), __('Import')],
        ];
        $btnAttr = array_merge($btnAttr, $attr);
        $html = [];
        foreach ($btns as $k => $v) {
            //如果未定义或没有权限
            if (!isset($btnAttr[$v]) || ($v !== 'refresh' && !$auth->check("{$controller}/{$v}"))) {
                continue;
            }
            list($href, $class, $icon, $text, $title) = $btnAttr[$v];
            //$extend = $v == 'import' ? 'id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"' : '';
            //$html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '" ' . $extend . '><i class="' . $icon . '"></i> ' . $text . '</a>';
            if ($v == 'import') {
                $template = str_replace('/', '_', $controller);
                $download = '';
                if (file_exists("./template/{$template}.xlsx")) {
                    $download .= "<li><a href=\"/template/{$template}.xlsx\" target=\"_blank\">XLSX模版</a></li>";
                }
                if (file_exists("./template/{$template}.xls")) {
                    $download .= "<li><a href=\"/template/{$template}.xls\" target=\"_blank\">XLS模版</a></li>";
                }
                if (file_exists("./template/{$template}.csv")) {
                    $download .= empty($download) ? '' : "<li class=\"divider\"></li>";
                    $download .= "<li><a href=\"/template/{$template}.csv\" target=\"_blank\">CSV模版</a></li>";
                }
                $download .= empty($download) ? '' : "\n                            ";
                if (!empty($download)) {
                    $html[] = <<<EOT
                        <div class="btn-group">
                            <button type="button" href="{$href}" class="btn btn-info btn-import" title="{$title}" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="{$icon}"></i> {$text}</button>
                            <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" title="下载批量导入模版">
                                <span class="caret"></span>
                                <span class="sr-only">Toggle Dropdown</span>
                            </button>
                            <ul class="dropdown-menu" role="menu">{$download}</ul>
                        </div>
EOT;
                } else {
                    $html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="' . $icon . '"></i> ' . $text . '</a>';
                }
            } else {
                $html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '"><i class="' . $icon . '"></i> ' . $text . '</a>';
            }
        }
        return implode(' ', $html);
    }
}

if (!function_exists('build_heading')) {

    /**
     * 生成页面Heading
     *
     * @param string $path 指定的path
     * @return string
     */
    function build_heading($path = null, $container = true)
    {
        $title = $content = '';
        if (is_null($path)) {
            $action = request()->action();
            $controller = str_replace('.', '/', request()->controller());
            $path = strtolower($controller . ($action && $action != 'index' ? '/' . $action : ''));
        }
        // 根据当前的URI自动匹配父节点的标题和备注
        $data = Db::name('auth_rule')->where('name', $path)->field('title,remark')->find();
        if ($data) {
            $title = __($data['title']);
            $content = __($data['remark']);
        }
        if (!$content) {
            return '';
        }
        $result = '<div class="panel-lead"><em>' . $title . '</em>' . $content . '</div>';
        if ($container) {
            $result = '<div class="panel-heading">' . $result . '</div>';
        }
        return $result;
    }
}
